package com.wzy.handler;

import com.wzy.exception.SystemException;
import com.wzy.util.RedisCache;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.wzy.constant.RedisConstants.REDIS_LOGIN_KEY;
import static com.wzy.constant.SystemConstants.TOKEN_KEY;
import static com.wzy.enums.AppHttpCodeEnum.NEED_LOGIN;

/**
 * 登录拦截器
 */
@Slf4j
@RequiredArgsConstructor
public class UserLoginInterceptor implements HandlerInterceptor
{

    private final RedisCache redisCache;

    /***
     * 在请求处理之前进行调用(Controller方法调用之前)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    {
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod()))
        {
            log.debug("OPTIONS请求，放行");
            return true;
        }
        log.debug("执行了拦截器的preHandle方法");
        // token校验
        String token = request.getHeader(TOKEN_KEY);
        if (StringUtils.isAnyBlank(token))
        {
            throw new SystemException(NEED_LOGIN, "未登录，请登录后重试");
        }
        String tokenKey = REDIS_LOGIN_KEY + token;
        if (Boolean.FALSE.equals(redisCache.hasKey(tokenKey)))
        {
            throw new SystemException(NEED_LOGIN, "未登录，请登录后重试");
        }
        return true;
    }

}

